package com.tanhua.sso.service;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.asymmetric.RSA;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.File;

@Service
@Data
public class RSAService {

    @Value("${tanhua.rsa.dir}")
    private String rsaDir;

    private String privateKey;
    private String publicKey;

    @PostConstruct
    public void init() {
        String privateKeyPath = rsaDir + File.separator + "rsa";
        String publicKeyPath = rsaDir + File.separator + "rsa.pub";

        if(FileUtil.exist(privateKeyPath)) {
            privateKey = FileUtil.readString(privateKeyPath, CharsetUtil.CHARSET_UTF_8);
        }

        if(FileUtil.exist(publicKeyPath)) {
            publicKey = FileUtil.readString(publicKeyPath, CharsetUtil.CHARSET_UTF_8);
        }

        if(StrUtil.isAllEmpty(privateKey, publicKey)) {
            //公钥和私钥都没有，生成rsa文件
            RSA rsa = new RSA();
            //写数据到私钥文件
            FileUtil.writeString(rsa.getPrivateKeyBase64(), privateKeyPath, CharsetUtil.CHARSET_UTF_8);
            //写数据到公钥文件
            FileUtil.writeString(rsa.getPublicKeyBase64(), publicKeyPath, CharsetUtil.CHARSET_UTF_8);

            privateKey = FileUtil.readString(privateKeyPath, CharsetUtil.CHARSET_UTF_8);
            publicKey = FileUtil.readString(publicKeyPath, CharsetUtil.CHARSET_UTF_8);
        }
    }
}
